package cn.yunbamboos.rest.service.core;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.yunbamboos.exception.AppException;
import cn.yunbamboos.rest.service.IInDTOConverter;
import cn.yunbamboos.rest.service.ISession;
import cn.yunbamboos.rest.service.ISessionContainer;
import cn.yunbamboos.rest.service.converter.RequestConverterInDTO;
import cn.yunbamboos.rest.service.dto.in.BaseInDTO;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import java.util.List;

public class InDTOConverter implements IInDTOConverter {

    private static final Logger logger = LoggerFactory.getLogger(InDTOConverter.class);

    private final ISessionContainer sessionContainer;
    private final List<RequestConverterInDTO> requestConverters;

    public InDTOConverter(ISessionContainer sessionContainer, List<RequestConverterInDTO> requestConverters) {
        this.sessionContainer = sessionContainer;
        this.requestConverters = requestConverters;
    }

    @Override
    public BaseInDTO convert() {
        ISession session = sessionContainer.getSession();
        if (ObjUtil.isNull(session)) {
            throw AppException.c("session is null");
        }
        HttpServletRequest request = session.getRequest();
        String contentType = request.getContentType();
        if(StrUtil.isBlank(contentType)){
            contentType = MediaType.APPLICATION_JSON_VALUE;
        }
        MediaType mediaType = MediaType.parseMediaType(contentType);
        for (RequestConverterInDTO converter : requestConverters) {
            if (converter.supports(mediaType)) {
                return converter.converter();
            }
        }
        throw AppException.c("not supported MediaType({})", contentType);
    }
}
